package utils

import (
	"time"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/sync/singleflight"
)

type CustomClaims struct {
	BaseClaims
	BufferTime int64
	jwt.RegisteredClaims
}

type BaseClaims struct {
	UUID      string
	CompanyID int64
	RoleID    int64
	AK        string
}

type JWT struct {
	SigningKey  []byte
	BufferTime  int64
	ExpiresTime int64
	Issuer      string
}

func NewJWT(sign, Issuer string, bufferTime, ExpiresTime int64) *JWT {
	return &JWT{
		[]byte(sign),
		bufferTime,
		ExpiresTime,
		Issuer,
	}

}
func (j *JWT) CreateClaims(baseClaims BaseClaims) CustomClaims {
	claims := CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: j.BufferTime,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    j.Issuer,
			Subject:   baseClaims.UUID,
			Audience:  jwt.ClaimStrings([]string{baseClaims.AK}),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(j.ExpiresTime))),
			NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Second * 1000)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ID:        baseClaims.UUID,
		},
	}
	return claims
}

// CreateToken 创建一个token
func (j *JWT) CreateToken(claims CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
	return token.SignedString(j.SigningKey)
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JWT) CreateTokenByOldToken(oldToken string, claims CustomClaims) (string, error) {
	group := &singleflight.Group{}
	v, err, _ := group.Do("JWT:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

// ParseToken 解析 token
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		return nil, err
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, jwt.ErrTokenInvalidClaims

	} else {
		return nil, jwt.ErrTokenInvalidClaims

	}
}

func GetUserToken(ctx *app.RequestContext) BaseClaims {
	value, ok := ctx.Get("userToken")
	if ok {
		return value.(BaseClaims)
	} else {
		return BaseClaims{}
	}

}
